package com.chiang.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

/**
 * @author : 765819328@qq.com
 * @version :
 * @date : Created in 2021/7/19 8:52
 * @description: BIO模型
 * @modified By:
 */
public class BIOServer {
    //编写一个Handler方法，和客户端通讯
    public static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        //通过Socket 获取输入流
        try {

            InputStream inputStream = socket.getInputStream();
            //循环读取客户端发送的数据
            while (true) {
                System.out.println("while true");
                int read = inputStream.read(bytes);
                if (read != -1) {
                    String a = new String(bytes, 0, read);
                    System.out.println("线程信息 id=" + Thread.currentThread().getId() + " 名字=" + Thread.currentThread().getName());
                    System.out.println(a);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭 client的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //线程池
        //1、创建一个线程池
        //2、创建一个线程与之通讯
        ExecutorService executorService = Executors.newCachedThreadPool();
        //构造一个线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                1, 1, 10, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(1),
                new ThreadPoolExecutor.DiscardOldestPolicy());
        /*threadPool.execute(() -> {
            try {
                //执行 方法
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                threadPool.shutdown();// 关闭线程池
            }
        });*/
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了");
        while (true) {
            // 监听，等待客户端连接
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            //
            executorService.execute(() -> {
                //可以和客户端通讯
                handler(socket);
            });
        }

    }
}
